package core.android.deeplinks.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.ParseException;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import core.android.deeplinks.deeplinking.AKDeeplink;
import core.android.tools.AK;

/**
 * HokoApplinksActivity serves the purpose of receiving incoming appLinks intents and forwarding
 * them to the Deeplinking module where it will be parsed and start the associated activity.
 */
@SuppressLint("Registered")
public class DeeplinkSchemeActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String urlString = getIntent().getData().toString();

        AK.d(getLocalClassName(), "urlString=" + urlString);

        AKDeeplink.INSTANCE.initDeeplinking(getApplication());
        AKDeeplink.INSTANCE.openURL(urlString);

        onNewIntent(getIntent());
    }

    /**
     * 检验该intent是否是deep link的intent。如果是则从intent数据从接触recipe的URI并调用
     * showRecipe()来展示菜谱。
     **/

    @Override
    protected void onNewIntent(Intent intent) {
        String action = intent.getAction();
        String data = intent.getDataString();

        Log.d(this.getLocalClassName(), "action=" + action);
        Log.d(this.getLocalClassName(), "data=" + data);

        Uri referrerUri = this.getReferrer();
        Log.d(this.getLocalClassName(), "referrerUri=" + referrerUri);//referrerUri=android-app://com.android.browser
    }


    /**
     * 返回启动该Activity的引用者.
     */
    @Override
    public Uri getReferrer() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            return super.getReferrer();
        }
        return getReferrerCompatible();
    }

    /**
     * 在低于SDK 22版本时使用该方法获得引用者
     */
    private Uri getReferrerCompatible() {
        Intent intent = this.getIntent();
        Uri referrerUri = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
        if (referrerUri != null) {
            return referrerUri;
        }
        String referrer = intent.getStringExtra("android.intent.extra.REFERRER_NAME");
        if (referrer != null) {
            // 尝试parse引用者URL
            try {
                return Uri.parse(referrer);
            } catch (ParseException e) {
                return null;
            }
        }
        return null;
    }

}
